package com.hb.common.util;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * 读写配置文件工具类
 */
@Component
public class PropertiesUtil {

    @Resource
    private PathPermissions pathPermissions;

    private final Logger log = LoggerFactory.getLogger(PropertiesUtil.class);

    // 配置文件路径
    private final String PATH = "/data.properties";

    /**
     * 根据 key 读取 value
     */
    public String getValue(String key) {
        Properties properties = getProperties();
        return properties.getProperty(key);
    }

    /**
     * 根据 key 读取 value，提供默认值
     */
    public String getValue(String key, String defaultValue) {
        Properties properties = getProperties();
        return properties.getProperty(key, defaultValue);
    }

    /**
     * 设置 key=value
     */
    public void setValue(String key, String value) {
        Properties properties = getProperties();
        try (OutputStream out = new FileOutputStream(pathPermissions.getConfigPath() + PATH)) {
            properties.setProperty(key, value);
            properties.store(out, "set: " + key + "=" + value);
        } catch (Exception e) {
            log.error("Error setting property: {}", e.getMessage(), e);
        }
    }

    /**
     * 获取 Properties 对象
     */
    private Properties getProperties() {
        Properties properties = new Properties();
        loadProperties(properties);
        return properties;
    }

    /**
     * 加载 Properties 对象
     */
    private void loadProperties(Properties properties) {
        try (InputStream is = new FileInputStream(pathPermissions.getConfigPath() + PATH)) {
            properties.load(is);
        } catch (Exception e) {
            log.error("Error loading properties: {}", e.getMessage(), e);
        }
    }

}